<script setup lang="ts">

import router from "@/router";
import type {GetType} from "@/type/GetType";
import {deleteData, getAllRepair, getAllUsers, put} from "@/net";
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox, ElTable} from "element-plus";
import {Delete, EditPen} from "@element-plus/icons-vue"
import {zhCn} from 'element-plus/es/locale/index.mjs';
// 状态变量
const dialogUpdateVisible = ref(false);
const dataPicker = ref(new Date());

// 获得用户名
interface USER {
  username: string;
  uid: number;
}

const handlerNameSelectChange = (um: string) => {
  const index = USERS.findIndex(user => user.username === um);
  if (um in USERS) {
    UpdateRepair.uid = USERS[index].uid;
    UpdateRepair.name = USERS[index].username;
  }
}
const USERS = reactive<USER[]>([])
const getAllUser_name = async () => {
  try {
    const res: GetType = await getAllUsers('/api/user/getAllName');
    USERS.splice(0, USERS.length, ...res.message.filter((user: any) => user.name !== null));
  } catch (e) {
    console.log(e)
  }
};
// 获得房屋id ,address
const handlerAddressSelectChange = () => {
  const index = HOUSES.findIndex(house => house.address === UpdateRepair.address);
  if (UpdateRepair.address in HOUSES) {
    UpdateRepair.house_id = HOUSES[index].house_id;
    UpdateRepair.address = HOUSES[index].address;
  }
}

interface HOUSE {
  house_id: number;
  address: string;
}

const HOUSES = reactive<HOUSE[]>([])
const getAllHouse_id = async () => {
  try {
    const res: GetType = await getAllUsers('/api/house/getAllHouseIDAndAddress');
    HOUSES.splice(0, HOUSES.length, ...res.message.filter((house: any) => house.address !== null));
  } catch (e) {
    console.log(e)
  }
};

// 功能函数
const fetchRepairListAndRefresh = () => {
  getAllRepairData();
};
const handlerOperationResult = (success: boolean) => {
  if (success) {
    fetchRepairListAndRefresh();
  }
};

const closeUpdataDialog = () => {
  dialogUpdateVisible.value = false;
};

// 获取
interface repairType {
  id: number,
  issue: string,
  type: string,
  progress: string,
  priority: string,
  house_id: number,
  address: string,
  uid: number,
  name: string,
  time: string,
  remark: string
}

let repairData: repairType[] = reactive([])

const getAllRepairData = async () => {
  try {
    const res: GetType = await getAllRepair('api/repairstatus/getAll');
    repairData.splice(0, repairData.length, ...res.message);
  } catch (e) {
    console.log(e)
  }
}

// 修改
let UpdateRepair = reactive({
  id: 0,
  issue: '',
  type: '',
  progress: '',
  priority: '',
  house_id: 0,
  address: '',
  uid: 0,
  name: '',
  time: '',
  remark: ''
})


const handleUpdateRepair = (row: Partial<typeof UpdateRepair>) => {
  Object.keys(row).forEach((key) => {
    if (UpdateRepair.hasOwnProperty(key)) {
      (UpdateRepair as any)[key] = (row as any)[key];
    }
  })
  dialogUpdateVisible.value = true;
}
const submitUpdateRepair = () => {
  const index = repairData.findIndex(repair => repair.id === UpdateRepair.id);
  const house_id = HOUSES.findIndex(house => house.address === UpdateRepair.address);
  const uid = USERS.findIndex(user => user.username === UpdateRepair.name);
  try {
    UpdateRepair.house_id = house_id;
    UpdateRepair.uid = uid;
    UpdateRepair.time = dataPicker.value.toLocaleString();
    put('api/repairstatus/update', UpdateRepair, () => {
          repairData[index] = UpdateRepair;
          ElMessage.success("修改成功");
          closeUpdataDialog();
        },
        () => {
          ElMessage.warning("修改失败");
        })
  } catch (e) {
    ElMessage.error("修改失败");
  }
}

// 删除

const handleDeleteRepair = (index: number, row: repairType) => {
  ElMessageBox.confirm("你要删除该维修记录吗?", "提示", {
    icon: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    deleteData("api/repairstatus/delete", {id: row.id}, () => {
      ElMessage.success("删除成功");
      handlerOperationResult(true);
    }, () => {
      ElMessage.warning("删除失败,")
    }, () => {
      ElMessage.error("删除error")
    });
  }).catch((err) => {
    ElMessage.error(err)
  })
}

onMounted(() => {
  getAllRepairData();
})


// 枚举量

const ProgressOptions = ref([
  {text: '已完成', value: '已完成'},
  {text: '处理中', value: '处理中'},
  {text: '待处理', value: '待处理'},
  {text: '已取消', value: '已取消'},
]);

const priorityOptions = ref([
  {text: '高', value: '高'},
  {text: '中', value: '中'},
  {text: '低', value: '低'},
]);
//
const filterProgress = (value: string, row: any) => {
  if (!value) return true;
  return row.progress === value;
};
const filterPriority = (value: string, row: any) => {
  if (!value) return true;
  return row.priority === value;
};
</script>

<template>

  <div style="display: flex; flex-flow: row nowrap; justify-content: space-between; margin-bottom: 10px">
    <div>
      <span>维修管理 > 维修信息</span>
    </div>
    <div style="margin-right: 60px">
      <el-button type="primary" @click="router.push('/home/repairRegistration')">添加活动</el-button>
    </div>
  </div>

  <el-table ref="table" :data="repairData" style="width: 100%"
            height="70vh" border
  >
    <el-table-column type="index" label="序号"/>
    <el-table-column prop="issue" label="维修类型">
      <template #default="scope">
        <el-popover
            placement="top-start"
            title="维修问题"
            width="200"
            trigger="hover"
            :content="scope.row.remark"
        >
          <template #reference>
            <el-tag>{{ scope.row.issue }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="type" label="保修问题"/>
    <el-table-column prop="progress" label="维修进度"
                     :filters="ProgressOptions"
                     :filter-method="filterProgress">
      <template #default="scope">
        <el-tag
            :type="scope.row.progress === '已完成' ? 'success' : scope.row.progress === '已取消' ? 'danger' : 'warning'">
          {{ scope.row.progress }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="priority" label="优先级"
                     :filters="priorityOptions"
                     :filter-method="filterPriority">
      <template #default="scope">
        <el-tag :type="scope.row.priority === '高' ? 'danger' : scope.row.priority === '中' ? 'warning' : 'success'">
          {{ scope.row.priority }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="address" label="房屋地址"/>
    <el-table-column prop="name" label="报修人"/>
    <el-table-column prop="time" label="报修时间"/>
    <el-table-column prop="remark" label="备注"/>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button name="update" @click="handleUpdateRepair(scope.row)" type="warning" :icon="EditPen" circle/>
        <el-button name="delete" plain @click="handleDeleteRepair(scope.$index,scope.row)" type="danger" :icon="Delete"
                   circle/>
      </template>

    </el-table-column>
  </el-table>

  <!--  修改房屋  -->
  <el-dialog
      title="修改活动信息"
      :model-value="dialogUpdateVisible"
      width="50%"
      @close="closeUpdataDialog"
  >
    <el-form label-width="auto"
             label-position="left"
             label-suffix=":"
             style="width: 500px;  margin:0 auto;"
             :size="'large'"
             v-model="UpdateRepair"
             ref="formRef"
    >
      <el-form-item label="维修问题">
        <el-input disabled v-model="UpdateRepair.issue"/>
      </el-form-item>
      <el-form-item label="维修类型">
        <el-input disabled v-model="UpdateRepair.type"/>
      </el-form-item>
      <el-form-item :required="true" label="维修进度">
        <el-select v-model="UpdateRepair.progress"
                   placeholder="请选择"
                   prop="progress"
        >
          <el-option
              v-for="progress in ProgressOptions"
              :key="progress.value"
              :label="progress.text"
              :value="progress.text"
          />
        </el-select>
      </el-form-item>
      <el-form-item :required="true" label="维修优先级">
        <el-input disabled v-model="UpdateRepair.priority">
        </el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input disabled v-model="UpdateRepair.name">
        </el-input>
      </el-form-item>
      <el-form-item label="房屋地址">
        <el-input disabled v-model="UpdateRepair.address">
        </el-input>
      </el-form-item>
      <el-form-item label="维修时间">
        <el-input disabled v-model="UpdateRepair.time">
        </el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="UpdateRepair.remark"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUpdateRepair">确定</el-button>
        <el-button @click="dialogUpdateVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<style scoped>

</style>